﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using MayhemCore;
using MayhemWpf.ModuleTypes;
using MayhemWpf.UserControls;
using System.Windows.Threading;
using CommandMgr.Sdk;

namespace CommandEvent
{
    [DataContract]
    [MayhemModule("Remote Command", "Fires when a specific command is queued in the Command Manager")]
    public class CommandEvent : EventBase, IWpfConfigurable
    {
        [DataMember]
        private string commandName;

        private DispatcherTimer timer;

        public void OnSaved(WpfConfiguration configurationControl) 
        {
            var config = (CommandConfig)configurationControl;
            commandName = config.Command;

        }

        public string GetConfigString() { return commandName; }

        public WpfConfiguration ConfigurationControl
        {
            get { return new CommandConfig(commandName); }
        }

        protected override void OnLoadDefaults()
        {
            commandName = "Foo";

        }

        protected override void OnBeforeLoad() 
        {
        }


        protected override void OnAfterLoad()
        {
            timer = new DispatcherTimer();
            timer.Interval = new TimeSpan(0, 0, 5);
            timer.Tick += CheckCommandQueue;
        }

        protected override void OnEnabling(EnablingEventArgs e)
        {
            timer.Start();
        }

        protected override void OnDisabled(DisabledEventArgs e)
        {
            timer.Stop();
        }

        private void CheckCommandQueue(object sender, EventArgs e)
        {
            CommandMgr.Sdk.CommandMgr commMgr = new CommandMgr.Sdk.CommandMgr(CommandServiceConfig.Url());
            if (commMgr.Dequeue(commandName))
                Trigger();

        }

    }
}
